﻿using FunArts.EasyDevOps.Shared.Models.Enums;
using FunArts.EasyDevOps.Shared.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunArts.EasyDevOps.Shared.Models.SshClient.Command
{
    /// <summary>
    /// 添加环境变量
    /// </summary>
    public class AddEnvCommand:ILinuxCommand
    {
        public string EnvName { get; set; }
        public string EnvValue { get; set; }
        public string FileName { get; set; }

        public string BuildCommand(SystemVersionTypeEnum systemVersionType)
        {
            if (FileName.IsNullOrWhiteSpace())
            {
                throw new Exception("文件名不能为空！");
            }
            string envLine = EnvName.ToLower().Trim() == "path"
            ? $"export {EnvName}=\"${EnvName}:{EnvValue}\""
            : $"export {EnvName}=\"{EnvValue}\"";

            string bashScript = $@"if [ -f /etc/profile.d/{FileName}.sh ]; then
                                        # 检查变量是否已存在
                                        if grep -q '^export {EnvName}=' /etc/profile.d/{FileName}.sh; then
                                            # 更新现有变量
                                            sudo sed -i 's|^export {EnvName}=.*|{envLine}|' /etc/profile.d/{FileName}.sh
                                        else
                                            # 追加新变量
                                            echo '{envLine}' | sudo tee -a /etc/profile.d/{FileName}.sh
                                        fi
                                    else
                                        # 创建新文件
                                        echo '{envLine}' | sudo tee /etc/profile.d/{FileName}.sh
                                    fi
                                    chmod +x /etc/profile.d/{FileName}.sh";

            // 替换 Windows 换行符为 Unix 换行符
            return bashScript.Replace("\r\n", "\n");
        }
    }
}
